#!/usr/bin/python
# -*- coding: utf8 -*-
import urllib2
import sys
import json

from functools import wraps

def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
    """Retry calling the decorated function using an exponential backoff.

    http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
    original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry

    :param ExceptionToCheck: the exception to check. may be a tuple of
        exceptions to check
    :type ExceptionToCheck: Exception or tuple
    :param tries: number of times to try (not retry) before giving up
    :type tries: int
    :param delay: initial delay between retries in seconds
    :type delay: int
    :param backoff: backoff multiplier e.g. value of 2 will double the delay
        each retry
    :type backoff: int
    :param logger: logger to use. If None, print
    :type logger: logging.Logger instance
    """
    def deco_retry(f):

        @wraps(f)
        def f_retry(*args, **kwargs):
            mtries, mdelay = tries, delay
            while mtries > 1:
                try:
                    return f(*args, **kwargs)
                except ExceptionToCheck, e:
                    msg = "%s, Retrying in %d seconds..." % (str(e), mdelay)
                    if logger:
                        logger.warning(msg)
                    else:
                        print msg
                    time.sleep(mdelay)
                    mtries -= 1
                    mdelay *= backoff
            return f(*args, **kwargs)

        return f_retry  # true decorator

    return deco_retry

class mongorest:
    def __init__(self,url,database):
        '''
        @parm url string mongodb api接口的地址 http://x.x.x.x:28017
        @parm database string 数据库地址
        '''
        self.url = url
        self.database = database

    @retry(urllib2.URLError, tries=10, delay=1, backoff=2)
    def find(self,table,data):
        '''
        @parm table string 需要查询的table
        @parm data  dict filter的字典 like {"id":"xxxx","region":'xxxx'}
        '''
        filter = []
        for k,v in data.items():
            arg = 'filter_{0}={1}'.format(k,v)
            filter.append(arg)
        _filter = '&'.join(filter)
        _url = '{0}/{1}/{2}/?{3}'.format(self.url,self.database,table,_filter)
        request = urllib2.Request(_url)
        try:
            result = urllib2.urlopen(request)
        except urllib2.URLError as e:
            if hasattr(e, 'reason'):
                print 'We failed to reach a server.'
                print 'Reason: ', e.reason
            elif hasattr(e, 'code'):
                print 'The server could not fulfill the request.'
                print 'Error code: ', e.code
            return False
        else:
            response = json.loads(result.read())
            result.close()
            if response['rows']:
                return response['rows']
            print 'Error. No reuslt'
            return False
